import 'dart:typed_data';

import 'package:image/image.dart';

class FilterColorUtil {
  static final _redUp = 40 / 360;
  static final _redDown = 300 / 360;
  static final blueUp = 300 / 360;
  static final blueDown = 170 / 360;

  static Image filterColor(Image src, FilterType type) {
    var time = DateTime.now().millisecondsSinceEpoch;

    Uint8List p = src.getBytes();

    int sum = 0;
    for (int i = 0, len = p.length; i < len; i += 400) {
      sum += getLuminanceRgb(p[i], p[i + 1], p[i + 2]);
    }

    double threshold = sum / p.length * 400 - 35;
    print('sum:$sum,threshold:$threshold');

    for (int i = 0,
//            repColor = (255 - (255 - threshold) * 0.4).toInt(),
            repColor = 0xFF,
            len = p.length;
        i < len;
        i += 4) {
      if (type == FilterType.filterRed &&
          (p[i] != repColor || p[i + 1] != repColor || p[i + 1] != repColor)) {
        _fillRed(p, i, [repColor, repColor, repColor]);
      }
      if (type == FilterType.filterBlue &&
          (p[i] != repColor || p[i + 1] != repColor || p[i + 1] != repColor)) {
        _fillBlue(p, i, [repColor, repColor, repColor]);
      }
      if (type == FilterType.blackWhite &&
          (p[i] != repColor || p[i + 1] != repColor || p[i + 1] != repColor)) {
        int l = getLuminanceRgb(p[i], p[i + 1], p[i + 2]);
        l = l < threshold ? 0 : 0xFF;
        p[i] = l;
        p[i + 1] = l;
        p[i + 2] = l;
      }
    }

    print(
        '图片Bytes:${src.length},filterColor时间:${DateTime.now().millisecondsSinceEpoch - time}');

    return src;
  }

  static _fillRed(List<int> p, int index, List<int> rgbSemblance) {
    var hsv = rgbToHsl(p[index], p[index + 1], p[index + 2]);
    if ((hsv[0] < _redUp || hsv[0] > _redDown) &&
        hsv[1] > 0.1 &&
        hsv[2] > 0.2 &&
        hsv[1] * 0.7 + hsv[2] * 1.3 > 0.7) {
      p[index] = rgbSemblance[0];
      p[index + 1] = rgbSemblance[1];
      p[index + 2] = rgbSemblance[2];
    }
  }

  static _fillBlue(List<int> p, int index, List<int> rgbSemblance) {
    var hsv = rgbToHsl(p[index], p[index + 1], p[index + 2]);
    if ((hsv[0] < blueUp && hsv[0] > blueDown) &&
        hsv[1] > 0.03 &&
        hsv[2] > 0.2 &&
        hsv[1] * 0.5 + hsv[2] * 1.5 > 0.3) {
      p[index] = rgbSemblance[0];
      p[index + 1] = rgbSemblance[1];
      p[index + 2] = rgbSemblance[2];
    }
  }
}

enum FilterType { filterRed, filterBlue, blackWhite }
